"""
数据模型模块初始化
"""

from .base import BaseModel
from .task import Task
from .user import User
from .template import Template
from .history import History


def init_database():
    """初始化数据库"""
    from ..app import get_mongo_db
    
    db = get_mongo_db()
    if db is None:
        raise RuntimeError("数据库连接未初始化")
    
    # 创建集合（如果不存在）
    collections = ['tasks', 'users', 'templates', 'history']
    existing_collections = db.list_collection_names()
    
    for collection_name in collections:
        if collection_name not in existing_collections:
            db.create_collection(collection_name)
            print(f"创建集合: {collection_name}")
    
    # 创建索引
    create_indexes()


def create_indexes():
    """创建数据库索引"""
    from ..app import get_mongo_db
    
    db = get_mongo_db()
    if db is None:
        raise RuntimeError("数据库连接未初始化")
    
    # 任务集合索引
    db.tasks.create_index("task_id", unique=True)
    db.tasks.create_index("status")
    db.tasks.create_index("created_at")
    db.tasks.create_index("user_id")
    db.tasks.create_index([("status", 1), ("created_at", -1)])
    
    # 用户集合索引
    db.users.create_index("user_id", unique=True)
    db.users.create_index("email", unique=True, sparse=True)
    db.users.create_index("created_at")
    
    # 模板集合索引
    db.templates.create_index("template_id", unique=True)
    db.templates.create_index("name")
    db.templates.create_index("category")
    db.templates.create_index("is_active")
    
    # 历史记录集合索引
    db.history.create_index("user_id")
    db.history.create_index("task_id")
    db.history.create_index("created_at")
    db.history.create_index([("user_id", 1), ("created_at", -1)])
    
    print("数据库索引创建完成")


__all__ = [
    'BaseModel',
    'Task',
    'User', 
    'Template',
    'History',
    'init_database',
    'create_indexes'
]